package servlet;


import dao.OrderDao;
import dao.OrderItemDao;
import dao.factoty.DaoFactory;
import domain.Order;
import domain.OrderItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "FindOrderByIdServlet", value = "/FindOrderByIdServlet")
public class FindOrderByIdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从request中获取订单id的值
        String id = request.getParameter("id");
        // 从DaoFactory中获取一个OrderItemDao实现类的实例对象;
        OrderItemDao orderItemDao = DaoFactory.getOrderItemDaoInstance();
        // 从DaoFactory中获取一个OrderDao实现类的实例对象;
        OrderDao orderDao = DaoFactory.getOrderDAOInstance();
        Order order = null;
        List<OrderItem> items = null;
        try {
            // 调用OrderDao的findOrderById(String id)方法;
            order = orderDao.findOrderById(id);
            // 一个订单对应多个OrderItem
            // 调用OrderItem的findOrderItemByOrder(order)方法
            items = orderItemDao.findOrderItemByOrder(order);
            // 将orderItems对象添加到order对象中;
            order.setOrderItems(items);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 将查询到的订单信息order添加到request作用域;
        request.setAttribute("view", order);
        // 类似FindOrdersServlet中，将请求转发到home.jsp页面，并传递item参数，值为view；
        request.getRequestDispatcher("/admin/login/home.jsp?item="+"view").forward(request, response);
    }
}
